<?php
class User extends CI_Controller{
	public function __construct(){
		parent::__construct();
		$this->load->model('User_Model','u');
		
	}

	public function index(){
		$cap = $this->captcha();
		$this->session->set_flashdata('cap',$cap['word']);
		$this->load->view('login',array('cap'=>$cap['image']));
	}

	public function login(){
		$cap = strtolower($this->input->post('cap'));
		if($cap == strtolower($_SESSION['cap'])){
			$username = $this->input->post('username');
			$password = $this->input->post('password');
			if ($username && $password) {
				$user = $this->u->get($username);
				if($user){
					if(md5($password) == $user->password){
						$_SESSION['id'] = $user->id;
						$_SESSION['username'] = $username;
						redirect(site_url('welcome/index'));
					}else{
						$this->session->set_flashdata('err','密码错误');
						redirect(site_url('user/index'));
					}
				}else{
					$this->session->set_flashdata('err','用户名不存在');
					redirect(site_url('user/index'));
				}
			}else{
				$this->load->view('login');
			}
		}else{
			$this->session->set_flashdata('err','验证码有误');
			redirect(site_url('user/index'));
		}
	}

	public function logout(){

		unset($_SESSION['username']);
		redirect(site_url('user/index'));
	}

	// public function register(){
	// 	$username = $this->input->post('username');
	// 	$password = $this->input->post('password');
	// 	if ($username && $password) {
	// 		$user = $this->u->get($username);
	// 		if(!empty($user)){
	// 			$this->session->set_flashdata('err','用户名已存在');
	// 			redirect(site_url('user/register'));
	// 		}else{
	// 			$register = $this->u->set($username,$password);
	// 			if($register){
	// 				$this->session->set_flashdata('err','注册成功');
	// 				redirect(site_url('user/index'));
	// 			}
	// 		}
	// 	}else{
	// 		$this->load->view('register');
	// 	}
	// }

	public function captcha(){
		$this->load->helper('captcha');
		$vals = array(
			'img_path'			=>	'./captcha/',
			'img_url'			=>	base_url().'captcha/',
			'font_path'			=>	'./path/to/fonts/texb.ttf',
			'colors'			=>	array(
				'background'	=>	array(0, 255, 255),
				'border'		=>	array(255, 255, 255),
				'text'			=>	array(0, 0, 0),
				'grid'			=>	array(255, 0, 0)
			)
		);
		$cap = create_captcha($vals);
		return $cap;
	}

}